<template>
  <div class="customer-management-page">
    <!-- 查询筛选区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="请选择客户类别">
        <el-select v-model="searchForm.customerType" placeholder="全部">
          <el-option label="全部" value="" />
          <el-option label="华中地区" value="华中地区" />
          <el-option label="华北地区" value="华北地区" />
        </el-select>
      </el-form-item>
      <el-form-item label="输入客户编号/名称/联系人电话">
        <el-input v-model="searchForm.keyword" placeholder="模糊搜索" />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="searchForm.includeHistory">包含销售人员离职</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="text" @click="handleCustomerManagement">客户管理</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="handleBatchOperate">批量修改</el-button>
      <el-button type="primary" @click="handleDisable">禁用</el-button>
      <el-button type="primary" @click="handleEnable">启用</el-button>
      <el-upload class="upload-btn" action="/your-import-api" :show-file-list="false" @success="handleImportSuccess">
        <el-button type="primary">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="handleExport">导出</el-button>
      <el-button type="danger" @click="handleDelete">删除</el-button>
    </div>

    <!-- 客户表格 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDeleteSingle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="customerLevel" label="客户级别" width="80" />
      <el-table-column prop="customerCode" label="客户编号" width="100" />
      <el-table-column prop="customerName" label="客户名称" />
      <el-table-column prop="receivableTerms" label="收款条件" width="100" />
      <el-table-column prop="region" label="地区" width="100" />
      <el-table-column prop="salesPerson" label="销售人员" width="100" />
      <el-table-column prop="contactPerson" label="联系人" width="100" />
      <el-table-column prop="taxpayerId" label="纳税人识别号" width="180" />
      <el-table-column prop="bankAccount" label="银行账号" width="180" />
      <el-table-column prop="phone" label="手机" width="120" />
      <el-table-column prop="arrears" label="应收款余额" width="120" />
      <el-table-column prop="relatedLine" label="关联线路" width="100" />
      <el-table-column prop="province" label="省" width="80" />
      <el-table-column prop="city" label="市" width="80" />
      <el-table-column prop="district" label="区" width="80" />
      <el-table-column prop="deliveryAddress" label="送货地址" />
      <el-table-column prop="remark" label="备注" width="120" />
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 16px"
    />

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑客户信息" width="600px">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="客户级别">
          <el-input v-model="editForm.customerLevel" />
        </el-form-item>
        <el-form-item label="客户编号">
          <el-input v-model="editForm.customerCode" />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="editForm.customerName" />
        </el-form-item>
        <!-- 可继续补充其他需要编辑的字段 -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import {
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElUpload,
  ElPagination
} from 'element-plus';

// 模拟表格数据（修复重复键问题，保证键唯一）
const tableData = ref([
  {
    customerLevel: 'VIP客户',
    customerCode: '100000',
    customerName: '客户1',
    receivableTerms: '月结',
    region: '天津',
    salesPerson: '销售-小东',
    contactPerson: '张',
    taxpayerId: '91140302532324828M',
    bankAccount: 'ENCRYPT ADSM',
    phone: '159****1234',
    arrears: '11,525.11',
    relatedLine: '天津',
    province: '天津市',
    city: '和平区',
    deliveryAddress: '天津市和平区****',
    remark: ''
  },
  {
    customerLevel: '零售客户',
    customerCode: '100001',
    customerName: '客户2',
    receivableTerms: '月结',
    region: '广东省',
    salesPerson: '销售-小东',
    contactPerson: '李先生',
    taxpayerId: '',
    bankAccount: '',
    phone: '181****0000',
    arrears: '5,240.57',
    relatedLine: '广东省',
    province: '广州市',
    city: '海珠区',
    deliveryAddress: '广东省广州市海珠区****',
    remark: ''
  }
]);

const total = ref(tableData.value.length);
const currentPage = ref(1);
const pageSize = ref(10);
const searchForm = reactive({
  customerType: '',
  keyword: '',
  includeHistory: false
});
const editDialogVisible = ref(false);
const editForm = reactive({
  customerLevel: '',
  customerCode: '',
  customerName: ''
});
const selectedRows = ref([]);

// 查询
const handleSearch = () => {
  console.log('搜索条件：', searchForm);
  // 实际需调用接口筛选数据，这里仅打印
};

// 客户管理（示例）
const handleCustomerManagement = () => {
  ElMessage.info('客户管理功能待实现');
};

// 新增
const handleAdd = () => {
  ElMessageBox.prompt('请输入客户名称', '新增客户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(({ value }) => {
      const newRow = {
        customerName: value,
        customerLevel: '普通客户'
        // 补充其他默认字段
      };
      tableData.value.unshift(newRow);
      ElMessage.success('新增成功');
    })
    .catch(() => {
      ElMessage.info('取消新增');
    });
};

// 批量操作（示例）
const handleBatchOperate = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要操作的行');
    return;
  }
  ElMessage.info('批量修改功能待实现，选中行：' + JSON.stringify(selectedRows.value));
};

// 禁用（示例）
const handleDisable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要禁用的行');
    return;
  }
  ElMessage.info('禁用功能待实现，选中行：' + JSON.stringify(selectedRows.value));
};

// 启用（示例）
const handleEnable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要启用的行');
    return;
  }
  ElMessage.info('启用功能待实现，选中行：' + JSON.stringify(selectedRows.value));
};

// 导入成功回调（示例）
const handleImportSuccess = (response) => {
  console.log(response);
  ElMessage.success('导入成功');
  // 实际需更新 tableData，这里仅示例
};

// 导出（示例）
const handleExport = () => {
  ElMessage.info('导出功能待实现');
};

// 批量删除（原功能）
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行');
    return;
  }
  ElMessageBox.confirm(
    '此操作将永久删除选中客户，是否继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      tableData.value = tableData.value.filter(
        (item) => !selectedRows.value.includes(item)
      );
      selectedRows.value = [];
      ElMessage.success('删除成功');
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

// 表格多选
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 编辑
const handleEdit = (row) => {
  editDialogVisible.value = true;
  // 安全赋值，避免直接访问原型方法报错
  for (const key in row) {
    if (Object.prototype.hasOwnProperty.call(editForm, key)) {
      editForm[key] = row[key];
    }
  }
};

// 保存编辑
const handleEditSave = () => {
  // 找到对应行并更新（示例逻辑，实际可结合接口）
  const index = tableData.value.findIndex(item => item.customerCode === editForm.customerCode);
  if (index !== -1) {
    tableData.value[index] = { ...editForm };
  }
  ElMessage.success('保存成功');
  editDialogVisible.value = false;
};

// 单个客户删除
const handleDeleteSingle = (row) => {
  ElMessageBox.confirm(
    `确定要删除客户「${row.customerName}」吗？此操作不可恢复。`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      // 从表格数据中删除该客户
      tableData.value = tableData.value.filter(item => item.customerCode !== row.customerCode);
      ElMessage.success('删除成功');
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

// 分页（示例，实际结合接口）
const handleSizeChange = (val) => {
  pageSize.value = val;
  // 调用接口获取对应页数据，这里仅示例
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 调用接口获取对应页数据，这里仅示例
};
</script>

<style scoped>
.customer-management-page {
  padding: 20px;
  background-color: #fff;
}

.search-form {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.el-dialog__body {
  padding: 16px;
}
</style>